package cn.tworice.nlp.client;

import cn.tworice.nlp.config.NLPProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.nlp.v20190408.NlpClient;
import com.tencentcloudapi.nlp.v20190408.models.AnalyzeSentimentRequest;
import com.tencentcloudapi.nlp.v20190408.models.AnalyzeSentimentResponse;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


@Component
public class TencentNLP {

    private Credential credential;

    @Resource
    private NLPProperties nlpProperties;

    @PostConstruct
    public void init() {
        String secretId = (nlpProperties != null && nlpProperties.getTencentcloudSecretId() != null)
                ? nlpProperties.getTencentcloudSecretId()
                : System.getenv("TENCENTCLOUD_SECRET_ID");
        String secretKey = (nlpProperties != null && nlpProperties.getTencentcloudSecretKey() != null)
                ? nlpProperties.getTencentcloudSecretKey()
                : System.getenv("TENCENTCLOUD_SECRET_KEY");
        credential = new Credential(secretId, secretKey);
    }

    public JSONObject parse(String str) {
        try{
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("nlp.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            NlpClient client = new NlpClient(credential, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            AnalyzeSentimentRequest req = new AnalyzeSentimentRequest();
            req.setText(str);
            AnalyzeSentimentResponse resp = client.AnalyzeSentiment(req);
            // 输出json格式的字符串回包
            return JSON.parseObject(AnalyzeSentimentResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param str 分析字符串
     * @return int 1-褒义 -1贬义 0中性
     **/
    public int senta(String str) {
        JSONObject parse = this.parse(str);
        double positive = parse.getDoubleValue("Positive");// 褒义概率
        double neutral = parse.getDoubleValue("Neutral");// 中性概率
        double negative = parse.getDoubleValue("Negative");// 贬义概率
        if (positive > neutral && positive > negative) {
            return 1;
        }else if(negative>positive && negative>neutral){
            return -1;
        }else{
            return 0;
        }
    }

}
